package com.turnengine.client.local.group;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;

import com.javabi.common.lang.ThreadSafe;
import com.turnengine.client.local.faction.bean.IFaction;
import com.turnengine.client.local.group.bean.IGroup;

@ThreadSafe
public class GroupCache implements IGroupCache {

	private final Set<IGroup> groupSet = new ConcurrentSkipListSet<IGroup>();

	public GroupCache() {
	}

	public GroupCache(Collection<IGroup> groups) {
		addGroups(groups);
	}

	@Override
	public void clear() {
		groupSet.clear();
	}

	@Override
	public int size() {
		return groupSet.size();
	}

	@Override
	public boolean addGroup(IGroup group) {
		return groupSet.add(group);
	}

	@Override
	public boolean containsById(int id) {
		for (IGroup group : groupSet) {
			if (group.getId() == id) {
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean containsByName(String name) {
		for (IGroup group : groupSet) {
			if (group.getName().equals(name)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public IGroup getById(int id) {
		for (IGroup group : groupSet) {
			if (group.getId() == id) {
				return group;
			}
		}
		throw new IllegalArgumentException("id=" + id);
	}

	@Override
	public IGroup getByName(String name) {
		for (IGroup group : groupSet) {
			if (group.getName().equals(name)) {
				return group;
			}
		}
		throw new IllegalArgumentException("name: " + name);
	}

	@Override
	public List<IGroup> getByFactionId(int factionId) {
		List<IGroup> set = new ArrayList<IGroup>();
		for (IGroup group : groupSet) {
			if (group.getFactionId() == factionId) {
				set.add(group);
			}
		}
		return set;
	}

	@Override
	public List<IGroup> getByParentId(int groupId) {
		List<IGroup> set = new ArrayList<IGroup>();
		for (IGroup group : groupSet) {
			if (group.getParentId() == groupId) {
				set.add(group);
			}
		}
		return set;
	}

	@Override
	public Iterator<IGroup> iterator() {
		return getAll().iterator();
	}

	@Override
	public List<IGroup> getAll() {
		return new ArrayList<IGroup>(groupSet);
	}

	@Override
	public List<IGroup> getByFaction(IFaction faction) {
		return getByFactionId(faction.getId());
	}

	@Override
	public List<IGroup> getByParent(IGroup group) {
		return getByParentId(group.getId());
	}

	@Override
	public int addGroups(Collection<IGroup> groups) {
		int added = 0;
		for (IGroup group : groups) {
			if (addGroup(group)) {
				added++;
			}
		}
		return added;
	}

	@Override
	public String toString() {
		return getAll().toString();
	}

}
